<?php
require_once __DIR__ . '/../common/functions.php';
checkLogin();
global $pdo;

$action = $_REQUEST['action'] ?? '';
try {
    switch ($action) {
        // 新增风格
        case 'add':
            $data = [
                'theme_name' => trim($_POST['theme_name'] ?? ''),
                'primary_color' => trim($_POST['primary_color'] ?? ''),
                'secondary_color' => trim($_POST['secondary_color'] ?? ''),
                'font_family' => trim($_POST['font_family'] ?? ''),
                'layout_type' => intval($_POST['layout_type'] ?? 1),
                'is_default' => 0 // 新增风格默认不设为默认
            ];
            if (empty($data['theme_name']) || !preg_match('/^#[\dA-Fa-f]{6}$/', $data['primary_color'])) {
                error('风格名称不能为空，主色调格式错误（需为#xxxxxx）');
            }
            $stmt = $pdo->prepare("INSERT INTO style_config SET 
                theme_name=?, primary_color=?, secondary_color=?, font_family=?, layout_type=?, is_default=?");
            $stmt->execute(array_values($data));
            success([], '新增风格成功');
            break;

        // 设为默认
        case 'setDefault':
            $id = intval($_POST['id'] ?? 0);
            if ($id <= 0) error('无效ID');
            $pdo->beginTransaction();
            $pdo->exec("UPDATE style_config SET is_default=0"); // 取消所有默认
            $stmt = $pdo->prepare("UPDATE style_config SET is_default=1 WHERE id=?");
            $stmt->execute([$id]);
            $pdo->commit();
            success([], '已设为默认风格');
            break;

        // 删除风格
        case 'delete':
            $id = intval($_POST['id'] ?? 0);
            $stmt = $pdo->prepare("SELECT is_default FROM style_config WHERE id=?");
            $stmt->execute([$id]);
            $style = $stmt->fetch();
            if (!$style) error('风格不存在');
            if ($style['is_default']) error('不能删除默认风格');
            $stmt = $pdo->prepare("DELETE FROM style_config WHERE id=?");
            $stmt->execute([$id]);
            success([], '删除成功');
            break;

        default:
            error('无效操作');
    }
} catch (PDOException $e) {
    error('操作失败：' . $e->getMessage());
}